package com.jstyle.jclife.fragment;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Space;
import android.widget.TextView;

import com.github.zagum.expandicon.ExpandIconView;
import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarLayout;
import com.haibin.calendarview.CalendarView;
import com.jstyle.jclife.NetWork.NetWorkUtil;
import com.jstyle.jclife.R;
import com.jstyle.jclife.adapter.RankAdapter;
import com.jstyle.jclife.model.NetResultData;
import com.jstyle.jclife.model.RankData;
import com.jstyle.jclife.utils.DateUtil;
import com.jstyle.jclife.utils.NetWorkConast;
import com.jstyle.jclife.utils.SchedulersTransformer;
import com.jstyle.jclife.view.CalendarLinearLayout;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link RankDayFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class RankDayFragment extends BaseFragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.CalendarView_sleep_Month)
    CalendarView CalendarViewSleepMonth;
    @BindView(R.id.iv_rank_icon)
    ImageView ivRankIcon;

    @BindView(R.id.tv_rank_step)
    TextView tvRankStep;
    @BindView(R.id.tv_rank_pace)
    TextView tvRankPace;
    @BindView(R.id.tv_rank_duration)
    TextView tvRankDuration;
    @BindView(R.id.tv_rank_distance)
    TextView tvRankDistance;
    @BindView(R.id.ConstraintLayout_top)
    ConstraintLayout ConstraintLayoutTop;
    @BindView(R.id.RecyclerView_rank)
    RecyclerView RecyclerViewRank;
    @BindView(R.id.CalendarLinearLayout)
    com.jstyle.jclife.view.CalendarLinearLayout CalendarLinearLayout;
    @BindView(R.id.CalendarLayout)
    com.haibin.calendarview.CalendarLayout CalendarLayout;
    Unbinder unbinder;
    @BindView(R.id.bt_rankday_date)
    Button btRankdayDate;
    @BindView(R.id.rankday_ExpandIconView)
    ExpandIconView rankdayExpandIconView;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    List<TextView> list = new ArrayList<>();
    private final int sortType_Distance=0;
    private final int sortType_Step=1;
    private final int sortType_Pace=2;
    private final int sortType_Duration=3;
    private int sortType=sortType_Distance;
    private RankAdapter rankAdapter;

    public RankDayFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment RankDayFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static RankDayFragment newInstance(String param1, String param2) {
        RankDayFragment fragment = new RankDayFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_rank_day, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        return view;
    }

    private void init() {
        list.add(tvRankDistance);
        list.add(tvRankPace);
        list.add(tvRankDuration);
        list.add(tvRankStep);
        setSelected(tvRankDistance);

        rankdayExpandIconView.switchState();
        CalendarViewSleepMonth.setOnDateSelectedListener(new CalendarView.OnDateSelectedListener() {
            @Override
            public void onDateSelected(Calendar calendar, boolean isClick) {

                String date = calendar.getYear() + "." + String.format("%02d", calendar.getMonth()) + "." + String.format("%02d", calendar.getDay());
                btRankdayDate.setText(date);
                getRank(date);

            }
        });
        CalendarViewSleepMonth.setOnViewChangeListener(new CalendarView.OnViewChangeListener() {
            @Override
            public void onViewChange(boolean isMonthView) {
                rankdayExpandIconView.switchState();
            }
        });
    }

    private void updateData(List<RankData.DataBean> data){
        if(data==null)data=new ArrayList<>();
        if(rankAdapter==null){
            rankAdapter = new RankAdapter(data,RankAdapter.type_days);
            final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
            linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL);
            ColorDrawable colorDrawable = new ColorDrawable();
            colorDrawable.setColor(Color.parseColor("#d9d9d9"));
            dividerItemDecoration.setDrawable(colorDrawable);
            RecyclerViewRank.addItemDecoration(dividerItemDecoration);
            RecyclerViewRank.setLayoutManager(linearLayoutManager);
            RecyclerViewRank.setAdapter(rankAdapter);
        }else{
            rankAdapter.updateData(data);
        }

    }
    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }
    @OnClick({R.id.tv_rank_step, R.id.tv_rank_pace, R.id.tv_rank_duration, R.id.tv_rank_distance})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_rank_step:
                sortType=sortType_Step;
                setSelected(tvRankStep);
                break;
            case R.id.tv_rank_pace:
                sortType=sortType_Pace;
                setSelected(tvRankPace);
                break;
            case R.id.tv_rank_duration:
                sortType=sortType_Duration;
                setSelected(tvRankDuration);
                break;
            case R.id.tv_rank_distance:
                sortType=sortType_Distance;
                setSelected(tvRankDistance);
                break;



        }
    }
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

    }
    private void setSelected(TextView textView) {
        for (TextView tv : list) {
            tv.setSelected(textView == tv);
        }
        sortData(listRankData);
    }
    List<RankData.DataBean>listRankData;
    private void sortData(List<RankData.DataBean>listRankData) {
        if(listRankData==null||listRankData.size()==0)return;
        Collections.sort(listRankData, new Comparator<RankData.DataBean>() {
            @Override
            public int compare(RankData.DataBean o1, RankData.DataBean o2) {
                int result=0;
                switch (sortType){
                    case sortType_Distance:
                        result= o2.getDistance()-o1.getDistance()<0?-1:1;
                        break;
                    case sortType_Duration:
                        result=o2.getActiveTime()-o1.getActiveTime();
                        break;
                    case sortType_Pace:
                        int getActiveTime2=o2.getPace();
                        int minute2=getActiveTime2%256;
                        int second2=getActiveTime2/256;
                        int getActiveTime1=o1.getPace();
                        int minute1=getActiveTime1%256;
                        int second1=getActiveTime1/256;
                        result=o1.getPace()==0?1:(minute1*60+second1)-(minute2*60+second2);

                        break;
                    case sortType_Step:
                        result=o2.getStep()-o1.getStep();
                        break;
                }
                return result;
            }
        });
        updateData(listRankData);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick(R.id.bt_rankday_date)
    public void onViewClicked() {
        if (CalendarLayout.isExpand()) {
            CalendarLayout.shrink();
        } else {
            CalendarLayout.expand();
//            ScrollView.fling(0);
           RecyclerViewRank.smoothScrollToPosition(0);
        }
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    private void getRank(String date){
        Map<String,Object> map=new HashMap<>();
        map.put("day",date);
        map.put("actId","1");
        map.put(NetWorkConast.KEY_uid,NetWorkUtil.getUserId());
        NetWorkUtil.getInstance().getJstyleApi().getRank(map)
                .compose(SchedulersTransformer.<RankData>io2MainObservable())
                .subscribe(new Observer<RankData>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(RankData netResultData) {
                        List<RankData.DataBean> data= (List<RankData.DataBean>) netResultData.getData();
                        listRankData=data;
                        if(sortType!=sortType_Distance){
                            sortData(data);
                        }else{
                            updateData(data);
                        }

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
